package com.blockmeta.bbs.immodule.activity.chat;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;

import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.StatusBarUtils;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.umeng.dialog.BlockMessageShareData;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.DeepLinkUtils;
import com.blockmeta.bbs.baselibrary.utils.OpenFileUtil;
import com.blockmeta.bbs.businesslibrary.util.RouterActivityHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.activity.MarketAndF10SearchMoreActivity;
import com.blockmeta.bbs.immodule.activity.base.IMBaseActivity;
import com.blockmeta.bbs.immodule.adapter.ChatAdapter;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.corebean.IUserDomainService;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.net.api.ReportChatGroupMsgApi;
import com.blockmeta.bbs.immodule.widget.HongBaoCreateDialogFragment;
import com.blockmeta.bbs.immodule.widget.IMRecyclerView;
import com.blockmeta.bbs.immodule.widget.Popup_From_Bottom;
import com.blockmeta.bbs.immodule.widget.Popup_Msg_Operate;
import com.blockmeta.bbs.immodule.widget.chatboard.BaseChatBoard;
import com.blockmeta.bbs.immodule.widget.chatboard.KeyboardEvent;
import com.blockmeta.bbs.immodule.widget.chatboard.NormalChatBoard;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.hellobike.flutter.thrio.navigator.ThrioNavigator;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE;
import static com.blockmeta.bbs.immodule.Constants.CALL_CHAR;

/**
 * Created by author on 2019/3/25.
 * 基础聊天详情页面
 * 子类包含 临时聊天 和群聊天！
 */
public abstract class BaseChatActivity extends IMBaseActivity implements BaseChatBoard.OnOutPutListener {


    protected IMUserEntity mUser;
    @BindView(R2.id.rcv_chat_list)
    IMRecyclerView mRcvChatList;
    @BindView(R2.id.txt_newmsg_backward)
    TextView m_txt_newmsg_backward;
    @BindView(R2.id.txt_newmsg_forward)
    TextView m_txt_newmsg_forward;
    @BindView(R2.id.im_message_mainPanel)
    View mContentView;
    @BindView(R2.id.iv_friend_or_circle)
    ImageView mIvFriendOrCircleIcon;
    @BindView(R2.id.tv_title)
    TextView mTvTitle;

    IMMetaBase mIMMetaService;
    IUserDomainService mUserDomainService;
    public BaseChatBoard mCbKeyboard;

    public ChatAdapter mChatAdapter;

    public Context mContext;

    Popup_From_Bottom mPop;

    public long toUserId;
    public long locMessageId;
    private View mInflate;
    private Popup_Msg_Operate m_popupOperate;
    protected boolean mIsCreate = true;

    private List<String> reportActions = Arrays.asList("营销垃圾", "淫秽色情", "违法信息", "骚扰信息");
    //每页加载数量
    public int pageSize = 50;

    public long m_unReadCount;
    public long m_unReadMSgIndex;
    public long m_unReadForwardCount;
    private BaseQuickAdapter.UpFetchListener upFetchListener;


    @Override
    protected boolean showTitle() {
        return false;
    }


    @Override
    public void setStatusBarColor() {
        StatusBarUtils.setWindowStatusBarColor(this, R.color.color_FFF1F1F1);
        StatusBarUtils.setLightMode(this);
    }

    @Override
    public View setView() {
        mInflate = getLayoutInflater().inflate(R.layout.activity_chat, null);
        return mInflate;
    }

    @Override
    public void initSerilization() {

    }


    @Override
    protected void initialize() {
        super.initialize();
        toUserId = getToUserId();
        locMessageId = getIntent().getLongExtra(Params.MSGID, 0);

        mContext = this;
        mIMMetaService = IMApplicationContext.getIMMetaService();
        mUserDomainService = IMApplicationContext.getUserDomainService();
        mCbKeyboard = new NormalChatBoard();
        mCbKeyboard.bindToContent(mContentView)
                .setOnOutPutListener(this);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.cb_keyboard, mCbKeyboard);
        transaction.disallowAddToBackStack();
        //提交修改
        transaction.commit();

        //初始化聊天列表
        initAdapter();

        initListener();

        initPopup();

    }

    private long getToUserId() {
        long userId = 0;
        //如果是从flutter页面过来的
        Map<String, Object> data = (Map<String, Object>) getIntent().getSerializableExtra("NAVIGATION_ROUTE_SETTINGS");
        if (data != null && data.containsKey("params")) {
            Map<String, String> params = (Map<String, String>) data.get("params");
            userId = Long.parseLong(params.get("UserId"));
            return userId;
        }

        userId = getIntent().getLongExtra(Params.USER_TAG, 0);
        if(userId == 0){
            //防止一部分页面还是传int过来
            userId = getIntent().getIntExtra(Params.USER_TAG, 0);
        }
        if(userId == 0){
            //获取arouter传值过来的是string，只有子类能获取到
            userId = getUserIdFromBundle();
        }
        return userId;
    }

    protected abstract long getUserIdFromBundle();

    private void initPopup() {
        m_popupOperate = new Popup_Msg_Operate(mContext, new Popup_Msg_Operate.IIMSelectorMenu() {
            @Override
            public void onForward(ChatMessage msg) {

            }

            @Override
            public void onCopy(ChatMessage msg) {
                String content = msg.getContent();
                //获取剪贴板管理器
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData mClipData = ClipData.newPlainText("", content);
                cm.setPrimaryClip(mClipData);
                ToastUtil.show("复制成功:" + content);
            }

            @Override
            public void onDelete(ChatMessage msg) {
                IMApplicationContext.getChatMessageDomainService().deleteChatMessageById(msg.getId());
                List<ChatMessage> data = mChatAdapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).getId().equals(msg.getId())) {
                        mChatAdapter.remove(i);
                    }
                }
            }

            @Override
            public void onReply(ChatMessage msg) {

            }

            @Override
            public void onReport(final ChatMessage msg) {
                mPop = new Popup_From_Bottom(mContext, getWindow().getDecorView(), new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        ProgressBarUtil.showProgress(mContext);
                        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
                        HashMap<String, Long> params = new HashMap<>();
                        params.put("chat_group_id", Long.valueOf(toUserId));
                        params.put("report_user_id", Long.valueOf(AccountHelper.getUidInt()));
                        params.put("msg_id", msg.getChatMessageId());
                        params.put("type", Long.valueOf(position + 1));
                        String content = new Gson().toJson(params);
                        final RequestBody requestBody = RequestBody.create(mediaType, content);
                        LogUtils.i("authorkkk", "report" + content);

                        RetrofitFactory.getRetrofit().create(ReportChatGroupMsgApi.class)
                                .reportChatGroupMsg(requestBody)
                                .compose(RxUtil.<BaseCodeResponse<Object>>rxSchedulerHelper())
                                .compose(((RxAppCompatActivity) mContext).<BaseCodeResponse<Object>>bindToLifecycle())
                                .subscribe(new CommonSubscriber<BaseCodeResponse<Object>>(mContext) {
                                    @Override
                                    public void onNext(BaseCodeResponse<Object> response) {
                                        ToastUtil.show("举报成功");

                                        LogUtils.i("authorkkk", "report ok" + response);
                                    }
                                });
                        mPop.dismiss();
                    }
                }, reportActions, new Popup_From_Bottom.OnDismissListener() {
                    @Override
                    public void onDismissListener() {

                    }
                });
                mPop.show();

            }


        }, new Popup_Msg_Operate.OnDismissListener() {
            @Override
            public void onDismissListener() {

            }
        });
    }


    private void initAdapter() {
        mRcvChatList.setLayoutManager(new LinearLayoutManager(this));
        //列表被点击时收起键盘
        mRcvChatList.setOnListTouched(new IMRecyclerView.OnListTouched() {
            @Override
            public void onListTouched() {
                mCbKeyboard.hideKeyBoard();
            }
        });

        mChatAdapter = new ChatAdapter(this, null);

        mRcvChatList.setAdapter(mChatAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setStackFromEnd(true);
        mRcvChatList.setLayoutManager(linearLayoutManager);
        //开启下拉加载
        mChatAdapter.setUpFetchEnable(true);
        //设置加载位置
        mChatAdapter.setStartUpFetchPosition(1);
    }

    private void initListener() {

        //向上滚动
        m_txt_newmsg_backward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (null != mChatAdapter) {
                    scrollToNextMsgPoint(v);
                }
            }
        });

        //向下滚动
        m_txt_newmsg_forward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mChatAdapter) {
                    mRcvChatList.scollToPosition((int) (mChatAdapter.getItemCount() - 2 - m_unReadForwardCount));
                    m_unReadForwardCount = 0;
                    v.setVisibility(View.GONE);
                }
            }
        });


        mChatAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                final ChatMessage cm = mChatAdapter.getData().get(position);

                if(R.id.iv_left_avatar == view.getId()){
                    //对相应用户进行@
                    if(getChatType() == ChatMessage.MSG_TYPE_UCG){
                        mCbKeyboard.tag(CALL_CHAR, String.valueOf(cm.getFromId()));
                    }
                }else {
                    if (view != null) {
                        m_popupOperate.show(cm, view);
                    }
                }
                return true;
            }
        });
        mChatAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                //发送失败的点击事件
                if (R.id.send_tx_fail == view.getId()) {

                    ChatMessage chatMessage = mChatAdapter.getData().get(position);
                    if (chatMessage.getStatus() == ChatMessage.STATUS_FAIL_FRIEND_SHIELD
                            || chatMessage.getStatus() == ChatMessage.STATUS_FAIL_TEMP_SHIELD) {
                        ToastUtil.show("你被屏蔽无法发送");
                    } else if (chatMessage.getStatus() == ChatMessage.STATUS_FAIL_NOT_MEMBER) {
                        ToastUtil.show("你不是成员");
                    } else if (chatMessage.getStatus() == ChatMessage.STATUS_FAIL_CHATGROUP_DISBAND) {
                        ToastUtil.show("圈子被解散");
                    } else {
                        mIMMetaService.resendMessage(chatMessage, new IMMetaBase.MessageSendCallBack() {
                            @Override
                            public void fail(String msg) {
                                ToastUtil.show("发送失败");
                            }

                            @Override
                            public void success(ChatMessage chatMessage) {
                                if (mChatAdapter == null) return;
                                //删除了老的消息，添加了新的消息
                                mChatAdapter.remove(position);
                                mChatAdapter.addData(chatMessage);
                                scrollToEndNoSmooth();
                            }
                        });
                    }

                } else if (R.id.left_pic == view.getId() || R.id.right_pic == view.getId()) {

                    openImgPage(adapter, view, position);
                } else if (R.id.iv_left_avatar == view.getId()) {
                    ChatMessage chatMessage = mChatAdapter.getData().get(position);
                    IMUserEntity userEntity = mUserDomainService.getUser(chatMessage.getFromId(), Params.USER_PERSON);
                    //如果是服务号不能跳个人页面
                    if(userEntity != null && !userEntity.isCustomerService()){
                        RouterActivityHelper.openUserCenter(mContext, String.valueOf(chatMessage.getFromId()));
                    }
                } else if (R.id.chat_item_layout_content == view.getId() || R.id.left_chat_item_layout_content == view.getId()) {
                    //包含deeplink的采用这种方式跳转
                    String deepLink = (String) view.getTag();
                    if (TextUtils.isEmpty(deepLink)) {
                        return;
                    }
                    LogUtils.d("author" + "click chat item deeplink" + deepLink);
                    String regexUri = DeepLinkUtils.regexUri(deepLink);
                    Uri uri = Uri.parse(regexUri);
                    DeepLinkUtils.jumpToTarget(mContext, uri);

                } else if (R.id.chat_file_layout_content == view.getId() || R.id.left_chat_file_layout_content == view.getId()) {
                    //点击文件的view的事件
                    ChatMessage item = mChatAdapter.getData().get(position);

                    LogUtils.d("author" + "click chat item download" + item.toString());
                    if (item.getType() == ChatMessage.TYPE_RECEIVE && item.getContent().length() == 0) {
                        mIMMetaService.downLoadFile(item);
                    } else if (item.getType() == ChatMessage.TYPE_SEND && item.getContent().length() == 0) {
                        //发送的是文库url，需要先下载下来
                        mIMMetaService.downLoadFile(item);
                    } else {
                        File localFile = new File(item.getContent());
                        if (localFile.exists()) {
                            //打开文件
                            openLocalFile(item.getContent(), item.getFileType());
                        } else {
                            //如果下载过，但是被用户删除了，需要重新下载
                            item.setContent("");
                            mIMMetaService.downLoadFile(item);
                        }

                    }
                }
            }
        });


        upFetchListener = new BaseQuickAdapter.UpFetchListener() {
            @Override
            public void onUpFetch() {
                loadHistoryData(mChatAdapter);
            }
        };

        mChatAdapter.setUpFetchListener(upFetchListener);

        mRcvChatList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState == SCROLL_STATE_IDLE && !recyclerView.canScrollVertically(1)){
                    loadForwardHistoryData(mChatAdapter);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int firstVisibleItem = manager.findFirstVisibleItemPosition();
                if (firstVisibleItem <= m_unReadMSgIndex && firstVisibleItem != 0)//如果
                {
                    m_unReadCount = 0;
                    m_unReadMSgIndex = 0;
                    m_txt_newmsg_backward.setVisibility(View.GONE);
                }
                if (manager.findLastVisibleItemPosition() == manager.getItemCount() - 1) {
                    if(m_txt_newmsg_forward.isShown()){
                        m_unReadForwardCount = 0;
                        m_txt_newmsg_forward.setVisibility(View.GONE);
                    }
                }
            }
        });

    }

    private void openLocalFile(String localFilePath, int fileType) {

        LogUtils.d("author" + "openfile" + localFilePath);
        if (fileType == ChatMessage.TYPE_PDF) {
            RouterHelper.buildPath(RouterPath.PDF_ACTIVITY)
                    .withString(Constant.TWO, localFilePath)
                    .navigation(mContext);
        } else {
            OpenFileUtil.openAndroidFile(mContext, localFilePath);
        }
    }


    protected void scrollToNextMsgPoint(View v) {
        scrollToUnreadLocation(v);
    }

    protected void scrollToUnreadLocation(View v) {
        int msgInDataIndex = m_unReadMSgIndex < 0 ? 0 : (int) m_unReadMSgIndex;
        mRcvChatList.scollToPosition(msgInDataIndex + 1);
        v.setVisibility(View.GONE);
        m_unReadCount = 0;
        m_unReadMSgIndex = 0;
    }

    private void openImgPage(BaseQuickAdapter adapter, View view, int position) {
        ChatMessage chatMessage = mChatAdapter.getData().get(position);
        if (chatMessage == null) {
            return;
        }
        List<ChatMessage> data = adapter.getData();
        ArrayList<String> pics = new ArrayList<>();
        int imgIndex = 0, i = 0;
        for (ChatMessage message : data) {
            //如果是图片消息
            if (message.getContentType() == 1 && message.getFileType() <= 3) {
                if (message.getId().equals(chatMessage.getId())) {
                    //图片初始展示位置，就是点击的消息图片
                    position = i;
                }
                pics.add(message.getFilePath());
                i++;
            }
        }
        if (pics.size() > 0) {

            //如果图片数过大，会导致intent发送超过
            if (pics.size() > 10) {
                Constant.TempImgUrls = pics;
                pics = new ArrayList<>();
            }
            RouterHelper.buildPath(RouterPath.VIEWPAGER_ACTIVITY)
                    .withStringArrayList(Constant.ZERO, pics)
                    .withInt(Constant.ONE, position)
                    .navigation(mContext);
        }
    }


    //加载历史消息
    protected void loadHistoryData(final ChatAdapter chatAdapter) {
        LogUtils.d("author loadhistorydata");
        mRcvChatList.post(new Runnable() {
            @Override
            public void run() {
                long ltMsgId = 0;
                if (chatAdapter.getData().size() != 0) {
                    ltMsgId = chatAdapter.getItem(0).getId();
                }
                final List<ChatMessage> loadMoreMessage = IMApplicationContext.getChatMessageDomainService().getChatMessageList(AccountHelper.getUidInt(), toUserId, getChatType(), pageSize, ltMsgId, 0);
                chatAdapter.addData(0, loadMoreMessage);
                chatAdapter.setUpFetching(false);
            }
        });

    }


    //从当前页向前加载历史消息
    protected void loadForwardHistoryData(final ChatAdapter chatAdapter) {
        LogUtils.d("author loadForwardHistoryData");
        //只有是搜索消息进来的时候才需要加载，普通时候因为已经加载了最后的消息而不需要
        if(locMessageId != 0){
            mRcvChatList.post(new Runnable() {
                @Override
                public void run() {
                    long gtMsgId = 0;
                    if (chatAdapter.getData().size() != 0) {
                        gtMsgId = chatAdapter.getItem(chatAdapter.getData().size() - 1).getId();
                    }
                    final List<ChatMessage> loadMoreMessage = IMApplicationContext.getChatMessageDomainService().getChatMessageList(AccountHelper.getUidInt(), toUserId, getChatType(), pageSize, 0, gtMsgId);
                    chatAdapter.addData(loadMoreMessage);
                    chatAdapter.setUpFetching(false);
                }
            });

        }

    }

    private void loadUnifySizeHistoryData(final ChatAdapter chatAdapter, final long fetchSize) {
        LogUtils.d("author loadunifysizedata");
        mRcvChatList.post(new Runnable() {
            @Override
            public void run() {

                List<ChatMessage> loadMoreMessage = IMApplicationContext.getChatMessageDomainService().getChatMessageList(AccountHelper.getUidInt(), toUserId, getChatType(), (int) (fetchSize), 0, 0);
                chatAdapter.setNewData(loadMoreMessage);
                chatAdapter.setUpFetching(false);

                m_unReadMSgIndex = mChatAdapter.getData().size() - m_unReadCount;
                m_unReadMSgIndex = m_unReadMSgIndex > 0 ? m_unReadMSgIndex : 0;
            }
        });

    }

    /**
     * 获取未读消息，从数据库
     */
    void queryChatMsgData() {
        queryUnReadMsgs();

        laterScrollToEnd();

    }

    protected void laterScrollToEnd() {
        mRcvChatList.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollToEndNoSmooth();
            }
        }, 200);
    }

    public void scrollToEndNoSmooth() {
        LinearLayoutManager manager = (LinearLayoutManager) mRcvChatList.getLayoutManager();
        mRcvChatList.scollToPositionNow(manager.getItemCount() - 1);
        mChatAdapter.setUpFetchEnable(true);
    }

    @Override
    public void onBackPressed() {
        if (!mCbKeyboard.interceptBackPress()) {
            super.onBackPressed();
        }
    }

    @OnClick({R2.id.fl_back, R2.id.fl_next})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.fl_back) {
            finish();

        } else if (i == R.id.fl_next) {
            jumpToFriendOrCircleHome();

        } else {
        }
    }

    /**
     * 跳转到对方主页或者圈子详情页
     */
    abstract void jumpToFriendOrCircleHome();
    //--------------------------------------Socket相关----------------------


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mIMMetaService.register(this);
    }

    protected void queryUnReadMsgs() {
        m_unReadCount = IMApplicationContext.getChatMessageDomainService()
                .getUnReadCount(AccountHelper.getUidInt(),
                        toUserId, getChatType());
        if (m_unReadCount >= 10) {
            m_txt_newmsg_backward.setText(BaseApp.getApp().getString(R.string.social_im_newmsg_txt, m_unReadCount > 999 ? "999+" : String.valueOf(m_unReadCount)));
            m_txt_newmsg_backward.setVisibility(View.VISIBLE);
        }

        mChatAdapter.setUpFetchEnable(false);

        long fetchSize = (m_unReadCount / pageSize + ((m_unReadCount % pageSize) != 0 ? 1 : 0)) * pageSize;
        loadUnifySizeHistoryData(mChatAdapter, fetchSize == 0 ? pageSize : fetchSize);


    }


    @Override
    protected void onResume() {
        super.onResume();

        //进入页面获取数据
        if (mIsCreate) {
            //需要加载指定消息位置
            if (locMessageId != 0) {
                queryLocHistoryMsgData(locMessageId);
            } else {
                queryChatMsgData();
            }
        } else {
            //从下一页面返回

        }
    }

    private void queryLocHistoryMsgData(long locMessageId) {
        //获取记录存在的页数进行加载
        List<ChatMessage> currentChatMessage = IMApplicationContext.getChatMessageDomainService()
                .getLocChatMessageList(AccountHelper.getUidInt(), toUserId, getChatType(), pageSize, locMessageId);
        mChatAdapter.setNewData(currentChatMessage);
        //加载后一页的数据
        loadForwardHistoryData(mChatAdapter);
    }

    protected abstract int getChatType();

    @Override
    protected void onDestroy() {
        mIMMetaService.unregister(this);
        super.onDestroy();

    }

    @Override
    protected void onPause() {
        super.onPause();
        IMApplicationContext.getChatMessageDomainService()
                .updateChatMessageChecked(AccountHelper.getUidInt(),
                        toUserId, getChatType());
        IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_ReadAllMsgFromOne(toUserId, getChatType()));

    }

    //----------------------------------------数据回调相关------------------------
    //接收到在线消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_IMMessage eventImMessage) {
        onReceiveOnlineMessage(eventImMessage);

    }

    private void onReceiveOnlineMessage(IMMetaBase.Event_IMMessage eventImMessage) {
        ChatMessage onlineMessage = eventImMessage.m_message;
        if (!isBelongThisTalk(onlineMessage)) {
            return;
        }
        int status = onlineMessage.getStatus();
        if (status == ChatMessage.STATUS_FAIL_RATE_LIMIT){
            ToastUtil.show("消息发送频率过快");
            return;
        }
        if (status == ChatMessage.STATUS_FAIL_SERVER_CLOSE){
            ToastUtil.show("消息服务停用");
            return;
        }
        boolean needScrollToEnd = false;
        LinearLayoutManager manager = (LinearLayoutManager) mRcvChatList.getLayoutManager();
        //最后一项没有显示的情况，要显示向下按钮
        if (manager.findLastVisibleItemPosition() != manager.getItemCount() - 1) {
            m_unReadForwardCount += 1;
            m_txt_newmsg_forward.setText(BaseApp.getApp().getString(R.string.social_im_newmsg_txt, m_unReadForwardCount > 999 ? "999+" : String.valueOf(m_unReadForwardCount)));
            if (!m_txt_newmsg_forward.isShown()) {
                m_txt_newmsg_forward.setVisibility(View.VISIBLE);
            }

            if (m_txt_newmsg_backward.isShown()) {
                m_unReadCount = 0;
                m_txt_newmsg_backward.setVisibility(View.GONE);
            }
        } else {
            needScrollToEnd = true;
        }
        //更新UI
        mChatAdapter.addData(onlineMessage);

        if (needScrollToEnd) {
            int itemCount = manager.getItemCount();
            mRcvChatList.scollToPosition(itemCount - 1);
        }

    }

    private boolean isBelongThisTalk(ChatMessage onlineMessage) {
        if (onlineMessage.getType() == ChatMessage.TYPE_RECEIVE) {
            return (onlineMessage.getMsgType() == ChatMessage.MSG_TYPE_UU
                    && onlineMessage.getFromId() == toUserId) ||
                    (onlineMessage.getMsgType() == ChatMessage.MSG_TYPE_UCG
                            && onlineMessage.getChatGroupId() == toUserId);
        } else {
            return (onlineMessage.getMsgType() == ChatMessage.MSG_TYPE_UU
                    && onlineMessage.getToId() == toUserId) ||
                    (onlineMessage.getMsgType() == ChatMessage.MSG_TYPE_UCG
                            && onlineMessage.getChatGroupId() == toUserId);

        }


    }

    // 从其他页面发送消息，本页面需要加入该条消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_SendIMMessageUnCallback eventImMessage) {
        ChatMessage onlineMessage = eventImMessage.m_message;
        if (!isBelongThisTalk(onlineMessage)) {
            return;
        }
        if (mChatAdapter == null) return;
        mChatAdapter.addData(onlineMessage);
        scrollToEndNoSmooth();
    }

    //文件上传事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_FileUploadMessage event) {
        ChatMessage message = event.message;
        if (!isBelongThisTalk(message)) {
            return;
        }
        if (mChatAdapter == null) return;
        if (event.status == IMMetaBase.BEGIN_UPLOAD) {
            mChatAdapter.addData(message);
            scrollToEndNoSmooth();
        } else if (event.status == IMMetaBase.UPLOADING) {
            List<ChatMessage> data = mChatAdapter.getData();
            int size = data.size();
            for (int i = 0; i < size; i++) {
                ChatMessage chatMessage = data.get(i);
                if (chatMessage.getUuid().equals(message.getUuid())) {
                    chatMessage.setFilePath(message.getFilePath());
                    mChatAdapter.notifyItemChanged(i);
                    break;
                }
            }
        } else if (event.status == IMMetaBase.COMPLETE_UPLOAD) {
            List<ChatMessage> data = mChatAdapter.getData();
            int size = data.size();
            for (int i = 0; i < size; i++) {
                ChatMessage chatMessage = data.get(i);
                if (chatMessage.getUuid().equals(message.getUuid())) {
                    chatMessage.setFilePath(message.getFilePath());
                    mChatAdapter.notifyItemChanged(i);
                    break;
                }
            }
        } else if (event.status == IMMetaBase.ERROR_UPLOAD) {
            List<ChatMessage> data = mChatAdapter.getData();
            int size = data.size();
            for (int i = 0; i < size; i++) {
                ChatMessage chatMessage = data.get(i);
                if (chatMessage.getUuid().equals(message.getUuid())) {
                    chatMessage.setStatus(ChatMessage.STATUS_FAIL_TIMEOUT);
                    mChatAdapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }

    //文件下载事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_FileDownLoadMessage event) {
        ChatMessage message = event.message;
        if (!isBelongThisTalk(message)) {
            return;
        }
        if (mChatAdapter == null) return;
        if (event.status == IMMetaBase.BEGIN_DOWNLOAD) {
            List<ChatMessage> data = mChatAdapter.getData();
            int size = data.size();
            for (int i = 0; i < size; i++) {
                ChatMessage chatMessage = data.get(i);
                if (chatMessage.getUuid().equals(message.getUuid())) {
                    mChatAdapter.notifyItemChanged(i);
                    break;
                }
            }
        } else if (event.status == IMMetaBase.DOWNLOADING) {
            List<ChatMessage> data = mChatAdapter.getData();
            int size = data.size();
            for (int i = 0; i < size; i++) {
                ChatMessage chatMessage = data.get(i);
                if (chatMessage.getUuid().equals(message.getUuid())) {
                    chatMessage.setFilePath(message.getFilePath());
                    mChatAdapter.notifyItemChanged(i);
                    break;
                }
            }
        } else if (event.status == IMMetaBase.COMPLETE_DOWNLOAD) {
            List<ChatMessage> data = mChatAdapter.getData();
            int size = data.size();
            for (int i = 0; i < size; i++) {
                ChatMessage chatMessage = data.get(i);
                if (chatMessage.getUuid().equals(message.getUuid())) {
                    chatMessage.setContent(message.getContent());
                    mChatAdapter.notifyItemChanged(i);
                    //打开文件
                    openLocalFile(chatMessage.getContent(), chatMessage.getFileType());
                    break;
                }
            }
        } else if (event.status == IMMetaBase.ERROR_DOWNLOAD) {
            if (message.getType() == ChatMessage.TYPE_SEND) {
                ToastUtil.show("文库文件下载出错");
                return;
            }
            List<ChatMessage> data = mChatAdapter.getData();
            int size = data.size();
            for (int i = 0; i < size; i++) {
                ChatMessage chatMessage = data.get(i);
                if (chatMessage.getUuid().equals(message.getUuid())) {
                    ToastUtil.show("文件下载出错");
                    break;
                }
            }
        }
    }

    //接收到消息回执
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_ReceiptMessage eventSendReceipt) {
        LogUtils.i("author" + "BaseChatActivitu获取消息回执");
        onSendSuccessMessage(eventSendReceipt);
    }


    /**
     * 发送消息成功！
     *
     * @param eventSendReceipt
     */
    protected void onSendSuccessMessage(IMMetaBase.Event_ReceiptMessage eventSendReceipt) {
        if (mChatAdapter.getData().size() > 0) {
            List<ChatMessage> data = mChatAdapter.getData();
            int size = data.size();
            for (int i = 0; i < size; i++) {
                ChatMessage chatMessage = data.get(i);
                if (chatMessage.getUuid().equals(eventSendReceipt.uuid)) {
                    chatMessage.setStatus(eventSendReceipt.status);
                    mChatAdapter.notifyItemChanged(i);
                }
            }
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCommentEvent(IMMetaBase.Event_Comment_Data eventCode) {
        if (eventCode.eventCode == Params.IMEvent_Quit_Circle && eventCode.circleId == toUserId) {//退出圈子
            LogUtils.i("author" + "接收到退出圈子Event");
            finish();
        }
    }


    public void startActivityToViewPager(List<String> pics, int position) {
        RouterHelper.buildPath(RouterPath.VIEWPAGER_ACTIVITY)
                .withStringArrayList(Constant.ZERO, new ArrayList<String>(pics))
                .withInt(Constant.ONE, position)
                .navigation(mContext);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveMessageTimeout(IMMetaBase.Event_MessageTimeOut timeOut) {
        List<ChatMessage> data = mChatAdapter.getData();
        int size = data.size();
        for (int i = 0; i < size; i++) {
            ChatMessage chatMessage = data.get(i);
            if (chatMessage.getUuid().equals(timeOut.uuid)) {
                chatMessage.setStatus(ChatMessage.STATUS_FAIL_TIMEOUT);
                mChatAdapter.notifyItemChanged(i);
            }
        }
    }


    /**
     * @param type
     * @param subType
     * @param content 内容
     */
    @Override
    public void onOutPutText(int type, int subType, String content) {
        if (type == ChatMessage.CONTENT_TYPE_NORMAL) {
            //文字
            mIMMetaService.sendNormalMessage(getChatType(), toUserId, content, new IMMetaBase.MessageSendCallBack() {
                @Override
                public void fail(String msg) {
                    ToastUtil.show("发送失败");
                }

                @Override
                public void success(ChatMessage chatMessage) {
                    if (mChatAdapter == null) return;
                    mChatAdapter.addData(chatMessage);
                    scrollToEndNoSmooth();
                }
            });
        } else if (type == ChatMessage.CONTENT_TYPE_CUSTOM) {
            if (TextUtils.isEmpty(content)){
                Intent intent = new Intent(mContext, MarketAndF10SearchMoreActivity.class);
                intent.putExtra(Constant.ZERO,getChatType());
                intent.putExtra(Constant.ONE,subType);
                intent.putExtra(Constant.TWO,toUserId);
                startActivity(intent);
                return;
            }
            //自定义内容
            mIMMetaService.sendCustomMessage(getChatType(), toUserId, content, subType, new IMMetaBase.MessageSendCallBack() {
                @Override
                public void fail(String msg) {
                    ToastUtil.show("发送失败");
                }

                @Override
                public void success(ChatMessage chatMessage) {
                    if (mChatAdapter == null) return;
                    mChatAdapter.addData(chatMessage);
                    scrollToEndNoSmooth();
                }
            });
        }
    }

    /**
     * 图片发送和文件发送，先分开进行处理
     *
     * @param type
     * @param url
     */
    @Override
    public void onOutPutFile(int type, String url) {
        if (type == ChatMessage.TYPE_JPG || type == ChatMessage.TYPE_PNG) {
            File file = new File(url);
            if (file.exists() && file.isFile()) {
                long fileSize = file.length();
                if (fileSize > 20 * 1024 * 1024) {
                    ToastUtil.show("图片太大超过20m");
                    return;
                }
            } else {
                ToastUtil.show("图片不存在");
                return;
            }
            mIMMetaService.sendImageMessage(getChatType(), toUserId, url);
        } else {
            File file = new File(url);
            if (file.exists() && file.isFile()) {
                long fileSize = file.length();
                if (fileSize > 10 * 1024 * 1024) {
                    ToastUtil.show("文件太大超过10m");
                    return;
                }
            } else {
                ToastUtil.show("文件不存在");
                return;
            }
            mIMMetaService.sendFileMessage(getChatType(), toUserId, url);
        }

    }

    @Override
    public void onChatBoardEvent(int eventType) {

        if (eventType == KeyboardEvent.RED_ENVELOPE) {
            HongBaoCreateDialogFragment.showDialog(getSupportFragmentManager(), getChatType(), toUserId, new HongBaoCreateDialogFragment.OnOutPutListener() {
                @Override
                public void onOutPutText(int type, int messageId, String content) {
                    if (type == ChatMessage.CONTENT_TYPE_HONGBAO) {
                        //自定义内容
                        mIMMetaService.sendHongbao(getChatType(), toUserId, messageId, content, new IMMetaBase.MessageSendCallBack() {
                            @Override
                            public void fail(String msg) {
                                ToastUtil.show("发送失败");
                            }

                            @Override
                            public void success(ChatMessage chatMessage) {
                                if (mChatAdapter == null) return;
                                mChatAdapter.addData(chatMessage);
                                scrollToEndNoSmooth();
                            }
                        });

                    }

                }
            });

        } else if(eventType == KeyboardEvent.ACTIVITY) {
            if(getChatType() == ChatMessage.MSG_TYPE_UU){
                Log.d("flutterting", "openselectpage");
                ThrioNavigator.push("/home/select",
                        "test",
                        true,
                        (view) -> {
                            return null;
                        }
                );
            }else if(getChatType() == ChatMessage.MSG_TYPE_UCG){

                Map<String, Integer> map = new HashMap<>();
                map.put("circleId", (int) toUserId);
                Log.d("flutterting", "openselectpage");
                ThrioNavigator.push("/activity/create",
                        map,
                        true,
                        (v) -> {
                            return null;
                        }
                );
            }

        }


    }

    /**
     * 录制的语音或者是视频
     *
     * @param type
     * @param file
     */
    @Override
    public void onOutPutFile(int type, File file) {

    }

    public void onOutPutRemoteFile(String name, String url, int size) {
        mIMMetaService.sendRemoteFileMessage(getChatType(), toUserId, name, url, size, new IMMetaBase.MessageSendCallBack() {
            @Override
            public void fail(String msg) {
                ToastUtil.show("发送失败");
            }

            @Override
            public void success(ChatMessage chatMessage) {
                if (mChatAdapter == null) return;
                mChatAdapter.addData(chatMessage);
                scrollToEndNoSmooth();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.d("author" + "basechatactivity result" + requestCode + " " + resultCode);
        if (requestCode == Constant.CUSTOM_MESSAGE_CONTENT) {
            if (resultCode == 200) {
                onOutPutText(ChatMessage.CONTENT_TYPE_CUSTOM
                        , data.getIntExtra("type", 0), data.getStringExtra("content"));
            }
        } else if (requestCode == Constant.REMOTE_File_MESSAGE_CONTENT) {
            if (resultCode == 200) {
                String name = data.getStringExtra("name");
                String url = data.getStringExtra("url");
                int size = data.getIntExtra("size", 0);
                if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(url)) {
                    onOutPutRemoteFile(name, url, size);
                }
            }
        }
    }
}
